<template>
    <div>
        <canvas ref="canvas" :width="prop.width" :height="prop.height"></canvas>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
const TextMessage = ref()
const prop = defineProps(["width", "height"])
// const emits = defineEmits(["act"])
const canvas = ref()
onMounted(() => {
    act()
})
const act = () => {

    const cas = canvas.value.getContext("2d")
    square(cas)
    line(cas)
    point(cas)
    CanvasText(cas, 20)
}

// 绘制文本内容
const CanvasText = (cas, fontSize) => {
    TextMessage.value = Text(5)
    cas.font = `${fontSize}px 宋体`

    for (let index = 0; index < TextMessage.value.length; index++) {
        const num = randoms(-30, 30) // 初始化角度
        const Content = (canvas.value.width / 2 + fontSize * index) - (fontSize * TextMessage.value.length / 2 - fontSize / 2)
        cas.fillStyle = Color(0, 255)
        cas.textBaseline = "middle"
        cas.translate(Content, canvas.value.height / 2)
        cas.rotate(num * Math.PI / 180)
        cas.fillText(TextMessage.value.charAt(index), 0, 0)
        cas.rotate(-num * Math.PI / 180)
        cas.translate(-Content, -canvas.value.height / 2)
    }

}
defineExpose({ TextMessage, act })

// 生成随机内容
const Text = (num) => {
    let str = "";
    for (let index = 0; index < num; index++) {
        str += randoms(0, 10)
    }
    return str
}
// 绘制干扰线
const line = (cas) => {
    for (let index = 0; index < 6; index++) {
        cas.beginPath()
        cas.moveTo(randoms(0, canvas.value.width), randoms(0, canvas.value.height))
        cas.lineTo(randoms(0, canvas.value.width), randoms(0, canvas.value.height))
        cas.strokeStyle = Color(0, 255)
        cas.stroke()
    }
}
// 绘制干扰点
const point = (cas) => {
    for (let index = 0; index < 15; index++) {
        cas.beginPath()
        cas.arc(randoms(0, canvas.value.width), randoms(0, canvas.value.height), 1, 0, Math.PI * 360 / 180, false)
        const color = Color(0, 255)
        cas.fillStyle = color;//设置填充颜色
        cas.fill();//开始填充
        cas.strokeStyle = color;//将线条颜色设置为蓝色
        cas.closePath()
        cas.stroke()
    }
}
// 绘制一个正方形
const square = (cas) => {
    cas.beginPath()
    cas.fillStyle = Color(0, 255)
    cas.fillRect(0, 0, 120, 50)
}

// 生成随机颜色
const Color = (min, max) => {
    let r = randoms(min, max)
    let b = randoms(min, max)
    let g = randoms(min, max)
    return "rgb(" + r + "," + g + "," + b + ")"

}

// 生成一个随机数
const randoms = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min)
}

</script>

<style scoped></style>